import collections


def json_get(ref, *keys):
    for key in keys:
        if type(key) == str:
            if type(ref) != dict:
                return None
            if key not in ref:
                return None
        else:
            if type(ref) != list:
                return None
            if len(ref) <= key:
                return None
        ref = ref[key]
    return ref


def json_set(ref, value, *keys):
    for i in range(len(keys) - 1):
        key = keys[i]
        if type(key) == str:
            if not type(ref) != dict:
                return False
            if key not in ref:
                return False
        else:
            if not type(ref) != list:
                return False
            if len(ref) <= key:
                return False
        ref = ref[key]
    if ref is None:
        return False
    ref[keys[-1]] = value
    return True


def compare_version(ver1, ver2):
    ver1 = ver1.split(".")
    len1 = len(ver1)
    for i in range(len1):
        ver1[i] = int(ver1[i])

    ver2 = ver2.split(".")
    len2 = len(ver2)
    for i in range(len2):
        ver2[i] = int(ver2[i])

    while len1 < len2:
        ver1.append(0)
        len1 += 1
    while len2 < len1:
        ver2.append(0)
        len2 += 1

    for i in range(len1):
        if ver1[i] != ver2[i]:
            return ver1[i] - ver2[i]
    return 0


def parse_macros (data):
    defs = {}
    for item in data.split(","):
        if len(item) == 0:
            continue
        kv = item.split("=")
        if len(kv) == 1:
            kv.append(1)
        defs[kv[0]] = kv[1]
    return defs


def parse_args(data):
    data = data.split()
    opts = collections.OrderedDict()
    args = []
    for frag in data:
        if frag.startswith("--"):
            frag = frag[2:].split("=")
            opts[frag[0]] = frag[1] if len(frag) > 1 else None
        elif frag.startswith("-"):
            opts[frag[1:2]] = frag[2:] if len(frag) > 2 else None
        else:
            args.append(frag)
    return opts, args


def merge_args(opts0, args0, opts1, args1):
    opts0 = opts0.copy()
    for k in opts1:
        if k in opts0 and opts0[k] == opts1[k]:
            opts0.pop(k)
        else:
            opts0[k] = opts1[k]
    args0 = args0.copy()
    for v in args1:
        args0.append(v)
    return opts0, args0
